package com.knife.oauth.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.knife.oauth.api.vo.IamMenuTree;
import com.knife.oauth.app.service.IamMenuService;
import com.knife.oauth.app.service.IamRoleMenuService;
import com.knife.oauth.domain.entity.IamMenu;
import com.knife.oauth.domain.entity.IamRoleMenu;
import com.knife.oauth.domain.entity.KnifeUserDetails;
import com.knife.oauth.infra.mapper.IamMenuMapper;
import com.knife.oauth.infra.mapper.IamRoleMenuMapper;
import com.knife.oauth.util.DetailHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色菜单关联(IamRoleMenu)应用服务
 *
 * @author tianhao.luo@hand-china.com
 * @since 2025-08-13 14:19:30
 */
@Service
public class IamRoleMenuServiceImpl implements IamRoleMenuService {

    @Resource
    private IamRoleMenuMapper iamRoleMenuMapper;
    @Resource
    private IamMenuService iamMenuService;
    @Resource
    private IamMenuMapper iamMenuMapper;

    @Override
    public Page<IamRoleMenu> selectList(Page<IamRoleMenu> pageRequest, IamRoleMenu iamRoleMenus) {
        return null;
    }

    @Override
    public void saveData(List<IamRoleMenu> iamRoleMenus) {

    }

    @Override
    public List<IamMenuTree> selectTree(Long tenantId) throws IllegalAccessException {
        KnifeUserDetails userDetails = DetailHelper.getUserDetails();
        LambdaQueryWrapper<IamRoleMenu> iamRoleMenuLambdaQueryWrapper = new LambdaQueryWrapper<>();
        assert userDetails != null;
        iamRoleMenuLambdaQueryWrapper.eq(IamRoleMenu::getRoleId, userDetails.getRoleId())
                .eq(IamRoleMenu::getTenantId, tenantId);
        List<IamRoleMenu> iamRoleMenus = iamRoleMenuMapper.selectList(iamRoleMenuLambdaQueryWrapper);
        List<Long> menuIdList = iamRoleMenus.stream().map(IamRoleMenu::getMenuId).collect(Collectors.toList());
        LambdaQueryWrapper<IamMenu> iamMenuLambdaQueryWrapper = new LambdaQueryWrapper<>();
        iamMenuLambdaQueryWrapper.in(IamMenu::getId, menuIdList)
                .eq(IamMenu::getType,0)
                .orderByAsc(IamMenu::getSort);
        List<IamMenu> iamMenus = iamMenuMapper.selectList(iamMenuLambdaQueryWrapper);
        return iamMenuService.buildTree(iamMenus);
    }
}

